package com.ruoyi.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.oms.entity.YytOmsOrder;
import com.ruoyi.common.oms.service.YytOmsOrderService;
import com.ruoyi.common.sms.service.YytSmsCouponHistoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis键过期监听器
 *
 * @author tanxingxian
 * @date 2022-01-11 11:04
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private YytOmsOrderService yytOmsOrderService;

    @Autowired
    private YytSmsCouponHistoryService yytSmsCouponHistoryService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();    // 生效的key
        String orderPrefix = "order:";
        System.out.println("失效的 key 是：" + key);
        if (key.contains(orderPrefix)) {
            String orderSn = key.replaceAll(orderPrefix, "");
            YytOmsOrder yytOmsOrder = yytOmsOrderService.getOne(new LambdaQueryWrapper<YytOmsOrder>().eq(YytOmsOrder::getOrderSn, orderSn));
            // 是否还是待付款
            if (yytOmsOrder.getStatus().equals(0)) {
                yytOmsOrder.setStatus(4);
                // 如果备注没有内容则加入关闭订单备注
                if (StringUtils.isBlank(yytOmsOrder.getNote())) {
                    yytOmsOrder.setNote("订单超时自动关闭");
                }
                yytOmsOrderService.updateById(yytOmsOrder);
                // 如果使用了优惠券，则把优惠券重置
                if(org.apache.commons.lang.StringUtils.isNotBlank(yytOmsOrder.getCouponId())){
                    yytSmsCouponHistoryService.upCouponModeStatus(yytOmsOrder.getCouponId(), yytOmsOrder.getId());
                }
            }
        }
    }

}
